import time
import random
import os

from django.shortcuts import render,reverse
from django.http import HttpResponse,JsonResponse
from django.db.models import Q
from django.core.paginator import Paginator

from .. import models

# 后台 - 用户管理

# 用户管理 - 列表
def userindex(request):
    # 通过模型获取数据
    data = models.Users.objects.all()


    # 搜索功能
    # 接收搜索条件
    selecttype = request.GET.get('selecttype',None)
    keywords = request.GET.get('keywords',None)
    # 有搜索条件
    if selecttype :
        # 根据ID/用户名/手机号进行搜索，导入Q模块
        if selecttype == 'all' :
            data = data.filter(
                    Q(id__contains=keywords)
                    |Q(username__contains=keywords)
                    |Q(phone__contains=keywords)
                    )
            # select * from users where id like '%keywords%' or username like '%keywords%' or phone like '%keywords%'
        # elif selecttype == 'id' :
        #     data = data.filter(id__contains=keywords)
        # elif selecttype == 'username' :
        #     data = data.filter(username__contains=keywords)
        # elif selecttype == 'phone' :
        #     data = data.filter(phone__contains=keywords)
        else :
            search = {f'{selecttype}__contains':keywords}
            data = data.filter(**search)


    # 分页功能
    # 导入Paginator模块，实例化分页对象
    p = Paginator(data,20)
    # 获取当前页
    page_index = request.GET.get('page',1)
    # 根据页码数获取当前页的数据
    data = p.page(page_index)


    # 分配数据
    context = {'data':data}

    # 加载模板
    return render(request,'myadmin/users/index.html',context)


# 用户管理 - 添加
def useradd(request):
    if request.method == 'GET' :
        # 显示添加表单
        return render(request,'myadmin/users/add.html')
    else :
        # 获取并处理用户输入的数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')

        # 对输入的密码进行加密
        from django.contrib.auth.hashers import make_password,check_password
        data['password'] = make_password(data['password'])
        # pbkdf2_sha256$260000$NThsk9zhT31Ahjz9lo2Llq$wcK69AqKmTNTM8PrPfDJQKjV1m5uulNy26GUz50V7HM=

        # 判断是否输入了头像
        if request.POST.get('face') == '' :
            data.pop('face')
        else :
            # 调用函数，上传头像
            data['face_url'] = uploadfile(request)

        # 调用模型，存储数据
        try:
            user = models.Users(**data)
            user.save()
            url = reverse('myadmin_userindex')
            return HttpResponse(f'<script>alert("添加成功");location.href="{url}"</script>')
        except:
            return HttpResponse('<script>alert("添加失败");history.go(-1)</script>')


# 用户管理 - 删除
def userdelete(request):
    try:
        # 获取需要删除的用户ID
        id = request.GET.get('id')
        obj = models.Users.objects.get(id=id)

        # 判断用户的头像是自定义头像还是默认头像
        if obj.face_url != '/static/myadmin/img/de_WOW.png' :
            try:
                # 删除自定义头像
                os.remove('.' + obj.face_url)
            except:
                return JsonResponse({'error':2,'msg':'头像删除失败'})

        # 执行删除
        obj.delete()
        return JsonResponse({'error':0,'msg':'删除成功'})

    except:
        return JsonResponse({'error':1,'msg':'删除失败'})


# 用户管理 - 修改
def useredit(request,uid):
    try:
        # 获取需要修改的用户对象
        obj = models.Users.objects.get(id=uid)
    except:
        return HttpResponse('<script>alert("参数错误");history.go(-1);</script>')

    if request.method == 'GET' :
        # 加载编辑表单
        return render(request,'myadmin/users/edit.html',{'userobj':obj})
    else :
        # 接收修改后的表单数据
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        print(data)

        # 检测是否需要更新头像
        if 'face' not in data :
            # 上传新的自定义头像
            data['face_url'] = uploadfile(request)
            # 判断是否需要删除之前的头像
            if obj.face_url != '/static/myadmin/img/de_WOW.png' :
                os.remove('.'+obj.face_url)
        else:
            data.pop('face')

        # 更新对象数据
        obj = models.Users.objects.filter(id=uid).update(**data)

        # 进行跳转
        url = reverse('myadmin_userindex')
        return HttpResponse(f'<script>alert("编辑成功");location.href="{url}";</script>')


# 封装函数，上传图片
def uploadfile(request,imgname='face'):
    # 上传头像
    myfile = request.FILES.get(imgname)
    if not myfile :
        return HttpResponse(f'<script>alert("没有上传文件");history.go(-1);</script>')
    # 获取文件后缀
    filetype = myfile.name.split('.').pop()
    # 限制上传的文件类型
    if filetype not in ['png', 'jpg', 'gif', 'jpeg','JPG','PNG','GIF','JPEG']:
        return HttpResponse('<script>alert("文件不是图片类型");history.go(-1);</script>')
    # 定义文件名
    filename = str(time.time()) + str(random.randint(10000, 99999)) + '.' + filetype
    try:
        # 上传文件
        with  open(f'./static/uploads/{filename}', 'wb+') as fp:
            fp.write(myfile.read())
        # 上传成功，返回上传图片的路径
        print(filename)
        return f'/static/uploads/{filename}'
    except:
        return HttpResponse(f'<script>alert("上传失败");history.go(-1);</script>')